<?php
class Del_View_Helper_Compress 
	extends Zend_View_Helper_Abstract
{

    public function compress()
    {
        return $this;
    }
    
	public function js()
	{
		$filesPath = getenv("DOCUMENT_ROOT") . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR;
		$minPath = $filesPath . DIRECTORY_SEPARATOR . 'min' . DIRECTORY_SEPARATOR;
		
		$config = Zend_Registry::get('configuration');
		
		if (! isset( $config->compress->js )){
			throw new Zend_Exception( __CLASS__ . ': no file list found on config file');
		}
		
		$jsFiles = $config->compress->js->toArray();
        $forceRegenerate = $config->compress->forceJsRegenerate;
		
		// recupero i file minificati scansionando la directory min
		$namespace = getenv("APPLICATION_ENV");
		$minFiles = array_slice(scandir($minPath), 2);
		$regenerate		= false;
		// controllo di avere i file minificati, nel qual caso
		// li ordino in base alla data; prendo poi il primo elemento
		// da utilizzare come comparazione per la validit�		
		$compare = 0;
		$fileToReturn = null;
		$filesToDelete	= array();
		
		if ( $minFiles ) {
			arsort( $minFiles );
			$filesToDelete = $minFiles;
			$fileToReturn = array_shift( $minFiles );
			$compare = filemtime($minPath.$fileToReturn);
			unset($minFiles);
		} else {
			$regenerate	= true;
		}
		
		// per ogni file che compone la minificazione,
		// ne controllo la reale esistenza e la data di modifica,
		// confrontandola con quella, eventualmente, del file da rigenerare
		
		if( !$regenerate && !$forceRegenerate && $this->_isOlder( $compare, $filesPath,  $jsFiles, 'js' )){
			$regenerate = true;
		}
		
		// se non esistono file minificati oppure � settata
		// la rigenerazione, rigenero il file
		if ($regenerate || $forceRegenerate ) {
			$tmp = "";
			
			foreach ($jsFiles as $jsFile){
				$tmp .= file_get_contents($filesPath.trim($jsFile).'.js');
			}
			
			$fileToReturn = $filename = implode('.', array($namespace, date('YmdHis'), 'js'));
			$tmp = My_Compressor_Js::minify($tmp);
			
			$this->_delete( $minPath, $filesToDelete);
			
			file_put_contents($minPath.$filename, $tmp);
		}
		
		$return = '/js/min/' . $fileToReturn;
		
		return $return;
	}
    
    
    
    public function css( $whiteLabelType = null, $whiteLabelName = null )
	{
		$filesPath	= getenv("DOCUMENT_ROOT") . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR;
		$minPath	= $filesPath . DIRECTORY_SEPARATOR . 'min' . DIRECTORY_SEPARATOR;
		$config		= Zend_Registry::get('configuration');
		
		if (! isset( $config->compress->css )){
			throw new Zend_Exception( __CLASS__ . ': no file list found on config file');
		}
		
		$namespace = getenv("APPLICATION_ENV");
		
		if( ! $whiteLabelType ){
		    $cssFiles = $config->compress->css->toArray();
		    
		} elseif( $whiteLabelType == 'negocio') {
		    
		    $cssFiles   = $config->compress->cssNegocio->toArray();
		    $cssFiles[] = "white-label/{$whiteLabelName}";
		    $namespace  ="-{$whiteLabelName}";
		    
		    
		}elseif( $whiteLabelType == 'cadena') {
		    $cssFiles	= $config->compress->cssCadena->toArray();
		    $cssFiles[] = "white-label/{$whiteLabelName}";
            $namespace  ="-{$whiteLabelName}";
		}
		
        $forceRegenerate= $config->compress->forceCssRegenerate;
		$minFiles		= array_slice(scandir($minPath), 2);
		
		// elimino los namespaces que no corresponden
		foreach( $minFiles as $k=>$minFile){
		    
		    $check = strstr($minFile, $namespace);
		    
		    if( ! $check ){
		        unset($minFiles[$k]);
		    }
		}
		
		$regenerate		= false;
		// controllo di avere i file minificati, nel qual caso
		// li ordino in base alla data; prendo poi il primo elemento
		// da utilizzare come comparazione per la validit�		
		$compare		= 0;
		$filesToDelete	= array();
		$fileToReturn	= null;
		
		if ( $minFiles ) {
			arsort($minFiles);
			$filesToDelete = $minFiles;
			$fileToReturn = array_shift( $minFiles );
			$compare = filemtime( $minPath . $fileToReturn );
			
			unset( $minFiles );
		} else {
			$regenerate = true;
		}

		
		// per ogni file che compone la minificazione,
		// ne controllo la reale esistenza e la data di modifica,
		// confrontandola con quella, eventualmente, del file da rigenerare
//		$files = explode(",", $css[$kName]);
		
		if( !$regenerate && !$forceRegenerate && $this->_isOlder( $compare, $filesPath,  $cssFiles, 'css' )){
			$regenerate = true;
		}
		
		// se non esistono file minificati oppure � settata
		// la rigenerazione, rigenero il file
		if ($regenerate || $forceRegenerate) {
			$tmp = "";
			foreach ($cssFiles as $cssFile){
				$tmp .= file_get_contents($filesPath.trim($cssFile).'.css');
			}
			
			$fileToReturn = $filename = implode('.', array($namespace, date('YmdHis'), 'css'));
			
			$tmp = My_Compressor_Css::minify($tmp);
			
			$this->_delete( $minPath, $filesToDelete);
			
			file_put_contents($minPath.$filename, $tmp);
		}
			 
		return '/css/min/' . $fileToReturn ;
	}
        
	
	protected function _delete( $path,  $files)
	{
		if( empty($files) ){
			return;
		}
		
		foreach ($files as $file){
			unlink( $path . $file );
		}
	}
	
	protected function _isOlder( $compare, $path,  $files, $ext )
	{
		
		foreach ($files as $file) {
			$file = $path . trim($file) . '.' . $ext;
			if (!file_exists( $file )){
				throw new Zend_Exception("Il file $file non esiste in $path");
			}
			else if (filemtime($file) > $compare) {
				return true;
			}
		}
		
		
	}

    
}